package com.hancher.gamelife5.money;

import android.app.Activity;

import androidx.annotation.NonNull;

import com.github.gzuliyujiang.calendarpicker.CalendarPicker;
import com.hancher.bean.MoneyDTO;
import com.hancher.money.R;
import com.hancher.money.databinding.DialogMoneyBinding;
import com.lxj.xpopup.core.CenterPopupView;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 描述 : 打卡弹窗 <br/>
 * 时间 : 2024/1/15 11:53 <br/>
 * 作者 : Hancher ytu_shaoweijie@163.com
 */
public class MoneyEditDialog extends CenterPopupView {

    private final OnSuccessClickListener listener;
    private final MoneyDTO moneyDTO;
    private final Activity mActivity;
    private DialogMoneyBinding binding;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy\nMM-dd");

    interface OnSuccessClickListener {
        void onSuccess(MoneyDTO moneyDTO);
    }


    public MoneyEditDialog(@NonNull Activity context, MoneyDTO moneyDTO, OnSuccessClickListener listener) {
        super(context);
        this.mActivity = context;
        this.moneyDTO = moneyDTO;
        this.listener = listener;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        binding = DialogMoneyBinding.bind(getPopupImplView());
        binding.tvDate.setOnClickListener(v1 -> {
            CalendarPicker picker = new CalendarPicker(mActivity);
            picker.setSelectedDate(System.currentTimeMillis());
            picker.setOnSingleDatePickListener(date -> {
                moneyDTO.setTradeTime(date.getTime());
                try {
                    binding.tvDate.setText(simpleDateFormat.format(date));
                } catch (Exception e) {
                }
            });
            picker.show();
        });
        binding.btnOk.setOnClickListener(v1 -> {
            moneyDTO.setMoney(Double.parseDouble(binding.etMoney.getText().toString()));
            moneyDTO.setNote(binding.etRemark.getText().toString());
            moneyDTO.setPerson(binding.etPerson.getText().toString());

            listener.onSuccess(moneyDTO);
            dialog.dismiss();
        });
        binding.imgType.setOnClickListener(v -> {
            moneyDTO.setMoneyInFlag(moneyDTO.getMoneyInFlag() == 1 ? 0 : 1);
            modifyType();
        });
        if (moneyDTO != null) {
            binding.etMoney.setText(moneyDTO.getMoney().toString());
            binding.etRemark.setText(moneyDTO.getNote());
            binding.tvDate.setText(simpleDateFormat.format(new Date(moneyDTO.getTradeTime())));
            binding.etPerson.setText(moneyDTO.getPerson());
            modifyType();
        }
    }

    private void modifyType() {
        binding.imgType.setImageResource(moneyDTO.getMoneyInFlag() == 1 ? R.drawable.icon_money_in : R.drawable.icon_money_out);
        binding.tvTitle.setText(moneyDTO.getMoneyInFlag() == 1 ? "收入" : "支出");
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_money;
    }
}
